<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\Student;
use App\Model\Teacher;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{

    public function loginPage()
    {
        if (Auth::guard('student')->id()) {
            return redirect('student');
        }
        else if (Auth::guard('teacher')->id()){
            return redirect('teacher');
        }else {
            return view('login');
        }

    }

    public function login(Request $request)
    {
        $phone = $request->input('phone');
        $password = $request->input('password');
        $studentModel = new Student();

        $user = $studentModel->where('phone', $phone)->first();
        $identity = 'student';
        if (!$user) {
            $teacherModel = new Teacher();
            $user = $teacherModel->where('phone', $phone)->first();
            if (!$user) {
                return $this->apiResponse(404, 'not found');
            }
            $identity = 'teacher';
            
        }

        if (!Hash::check($password, $user->password)) {
            return $this->apiResponse(403, '密码错误');
        }
        
        Auth::guard($identity)->login($user);
        
        
        return $this->apiResponse(200, 'success');
    }

    public function logout()
    {
        Auth::guard('student')->logout();
        Auth::guard('teacher')->logout();
        return redirect('/');
    }

    public function registerPage()
    {
        return view('register');

    }

    public function register(Request $request)
    {

        $name = $request->input('name');
        $studentId = $request->input('student_id');
        $phone = $request->input('phone');
        $password = $request->input('password');

        $studentModel = new Student();

        $student = $studentModel->where('phone', $phone)->first();

        if ($student) {
            return $this->apiResponse(403, '已经注册');
        }

        $student = $studentModel->create([
            'name' => $name,
            'phone' => $phone,
            'password' => bcrypt($password),
            'student_no' => $studentId
        ]);

        if ($student) {
            return $this->apiResponse(200, '注册成功');
        }

        return $this->apiResponse(500, '注册失败');




    }



}
